package com.zhx.real.security.validate.image;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.zhx.real.common.properties.security.EnableSecurityConfig;
import com.zhx.real.common.properties.security.SecurityProperties;
import com.zhx.real.security.validate.code.ValidateCodeGenerator;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.awt.image.BufferedImage;

/**
 * 验证码的生成器
 *
 * @author zhx
 * @create 2017-11-03 11:44
 **/
public class ImageCodeGenerator implements ValidateCodeGenerator {
	private EnableSecurityConfig enableSecurityConfig;

	private SecurityProperties securityProperties;

	@Override
	public String generate() {
		return null;
	}

	@Override
	public ImageCode generate(ServletWebRequest request) {
		/**
		 * 宽度
		 */
		String width = ServletRequestUtils.getStringParameter(request.getRequest(), "width",
				securityProperties.getValideDateCode().getImageCode().getWidth());
		/**
		 * 高度
		 */
		String height = ServletRequestUtils.getStringParameter(request.getRequest(), "height",
				securityProperties.getValideDateCode().getImageCode().getHeight());
		/**
		 * 长度
		 */
		int length = securityProperties.getValideDateCode().getImageCode().getLength();
		/**
		 * 设置验证码
		 */

		//生成验证码
		LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(Integer.parseInt(width), Integer.parseInt(height), 4, 10);

		lineCaptcha.setGenerator(new ImageCodeMacker(length,enableSecurityConfig.isDebug()));

		String createText = lineCaptcha.getCode();

		BufferedImage challenge = lineCaptcha.getImage();

		return new ImageCode(challenge,createText,securityProperties.getValideDateCode().getImageCode().getExpireIn());
	}

	public void setSecurityProperties(SecurityProperties securityProperties,EnableSecurityConfig enableSecurityConfig) {
		this.securityProperties = securityProperties;
		this.enableSecurityConfig = enableSecurityConfig;
	}

	public SecurityProperties getSecurityProperties() {
		return securityProperties;
	}
}
